package tech.aichan.AiQA.filter;

import cn.hutool.http.HttpStatus;
import tech.aichan.AiQA.constant.RedisConstant;
import tech.aichan.AiQA.exception.BusinessException;
import tech.aichan.AiQA.model.entity.login.LoginUser;
import tech.aichan.AiQA.properties.JwtProperties;
import tech.aichan.AiQA.utils.JwtUtil;
import tech.aichan.AiQA.utils.RedisCache;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Objects;

/**
 * @author mengyu
 * @date 2024/03/03 9:42
 * JWT过滤器
 */
@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Resource
    private RedisCache redisCache;
    @Resource
    private JwtProperties jwtProperties;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        SecurityContext context = SecurityContextHolder.getContext();
        if(!Objects.isNull(context.getAuthentication())){
            filterChain.doFilter(request, response);
            return;
        }
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(request, response);
            return;
        }
        Long userId = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(),token);
        log.info("parse jwt, userId :{}",userId);
        LoginUser user = redisCache.getCacheObject(RedisConstant.USER_LOGIN +userId);
        if(Objects.isNull(user)){
            throw new BusinessException(HttpStatus.HTTP_NOT_AUTHORITATIVE,"登录过期");
        }
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user,null,user.getAuthorities());
        context.setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);
    }
}
